<template>
  <van-cell-group>
    <van-cell
      title="&nbsp;&nbsp;聊天信息"
      is-link
      center
      size="large"
      @click="toFriendMsg(0)"
      ><van-badge
        class="dotClass"
        v-if="priAndTeamMsg"
        position="top-left"
        :offset="[0, 10]"
        dot
      />
      <template #icon>
        <van-icon
          name="comment-o"
          color="DeepSkyBlue"
          size="20"
          class="search-icon"
        />
      </template>
    </van-cell>
    <van-cell
      title="&nbsp;&nbsp;好友申请"
      is-link
      center
      size="large"
      @click="toFriendMsg(1)"
      ><van-badge
        class="dotClass"
        v-if="friendsMsg"
        position="top-left"
        :offset="[0, 20]"
        dot
      />
      <template #icon>
        <van-icon
          name="bulb-o"
          color="DeepSkyBlue"
          size="20"
          class="search-icon"
        />
      </template>
    </van-cell>
    <van-cell
      title="&nbsp;&nbsp;系统信息"
      is-link
      center
      size="large"
      @click="toFriendMsg(2)"
      ><van-badge
        class="dotClass"
        v-if="systemMsg"
        position="top-left"
        :offset="[0, 20]"
        dot
      />
      <template #icon>
        <van-icon
          name="service-o"
          color="DeepSkyBlue"
          size="20"
          class="search-icon"
        />
      </template>
    </van-cell> </van-cell-group
  ><van-loading v-if="loading" vertical>
    <template #icon>
      <van-icon name="star-o" size="30" />
    </template>
    加载中... </van-loading
  ><van-empty
    v-if="friendListData.length === 0"
    description="你还没有好友，快去添加几个吧"
  />
  <van-index-bar v-else>
    <template v-for="(item, index) in state.friendList" :key="index">
      <van-index-anchor
        :index="index"
        style="--van-index-anchor-font-size: 10px"
      />
      <template v-for="friend in item">
        <template @click="friendDetail(friend)" class="friend-items">
          <div class="avatar-container">
            <img :src="friend.friendUrl" class="avatar" />
          </div>
          <div class="friend-info">
            <div class="friend-name">
              {{ friend.note }}
              <div class="onLineOrNot">
                <template v-if="friend.onLine === 1">
                  <i class="onLinePoint"></i>
                  <span class="onLine">在线</span> </template
                ><template v-else
                  ><i class="notLinePoint"></i>
                  <span class="notLine">离线</span></template
                >
              </div>
            </div>
            <van-icon
              max="100"
              :size="28"
              name="chat-o"
              @click.stop="toChat(friend)"
            />
          </div>
        </template>
      </template>
    </template>
  </van-index-bar>
  <p style="text-align: center; font-size: 16px">
    共有{{ friendListData.length }}位好友
  </p>
</template>
<script setup lang="ts">
import { markRaw, reactive, ref, toRefs, watchEffect } from "vue";
import { UserType } from "../models/user";
import myAxios from "../plugins/myAxios";
import { pinyin } from "pinyin-pro";
import { getCurrentUser } from "../services/user";
import { showFailToast } from "vant";
import { useRouter } from "vue-router";
import { FriendsType } from "../models/friends";

/**
 * 去查看好友申请信息
 */
const router = useRouter();
const toFriendMsg = (active: number) => {
  router.push({
    path: "/message",
    query: {
      active,
    },
  });
};

/**
 * 访问好友主页
 */
const friendDetail = (friend: {}) => {
  router.push({
    path: "/user",
    query: {
      friendInfo: JSON.stringify(friend),
    },
  });
};

/**
 * 与好友私聊
 */
const toChat = (friend: FriendsType) => {
  router.push({
    path: "/chat",
    query: {
      scope: 1,
      friendId: friend.friendId,
      friendInfo: JSON.stringify(friend),
      friendly: true,
    },
  });
};

/**
 * 以备注首字母排列好友列表
 */
const state = reactive({
  friendList: {
    A: [],
    B: [],
    C: [],
    D: [],
    E: [],
    F: [],
    G: [],
    H: [],
    I: [],
    J: [],
    K: [],
    L: [],
    M: [],
    N: [],
    O: [],
    P: [],
    Q: [],
    R: [],
    S: [],
    T: [],
    U: [],
    V: [],
    W: [],
    X: [],
    Y: [],
    Z: [],
    "#": [],
  } as any,
  currentUser: {} as UserType,
});

/**
 * 将用作展示的对象列表以拼音首字母分组
 */
const friendListData = ref([]); //接收后端传来的好友列表
const doFriendList = async () => {
  friendListData.value.forEach((friend) => {
    const first = pinyin(friend.note.substring(0, 1), {
      toneType: "none",
      pattern: "first",
    }).toUpperCase();
    state.friendList[/^[A-Z]$/.test(first) ? first : "#"].push(friend);
  });
};

const loading = ref(false);
watchEffect(async () => {
  loading.value = true;
  state.currentUser = await getCurrentUser("1");
  const res = await myAxios.get("/friends/list", {
    params: {
      userId: state.currentUser.id,
    },
  });
  if (res.code === 0 && res.data) {
    friendListData.value = res.data;
    await doFriendList();
    state.updateFlag.foo = new Date().getTime();
  } else {
    showFailToast(`小智遗憾告知:${res.message}`);
  }
  getchatStatus();
  loading.value = false;
});
const updateFlag = markRaw(reactive({}));
state.updateFlag = toRefs(updateFlag);

/**
 * 消息提醒
 */
const priAndTeamMsg = ref(false); //私聊和队伍消息
const friendsMsg = ref(false); //好友申请消息
const systemMsg = ref(false); //系统消息
const getchatStatus = async () => {
  const res = await myAxios.get("/chat/chatStatus", {
    params: {
      userId: state.currentUser.id,
    },
  });
  if (res.code === 0) {
    const str = res.message;
    if (str.indexOf("1") !== -1) priAndTeamMsg.value = true;
    if (str.indexOf("4") !== -1) friendsMsg.value = true;
    if (str.indexOf("3") !== -1) systemMsg.value = true;
  }
};
</script>

<style scoped>
@import "../assets/css/friend.css";
</style>
